# coding=utf-8
import datetime
from django.db import models
from django.dispatch import receiver


class A(models.Model):
    name = models.CharField(max_length=30)
    count = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        print 'A.save ', datetime.datetime.now()
        super(A, self).save(*args, **kwargs)
        print 'A.save ', datetime.datetime.now()

    def delete(self, *args, **kwargs):
        super(A, self).delete(*args, **kwargs)
        print 'A.delete ', datetime.datetime.now()


class B(models.Model):
    a = models.ForeignKey('A')
    number = models.IntegerField(default=100)

    def save(self, *args, **kwargs):
        super(B, self).save(*args, **kwargs)
        print 'B.save ', datetime.datetime.now()

    def delete(self, *args, **kwargs):
        super(B, self).delete(*args, **kwargs)
        print 'B.delete ', datetime.datetime.now()

class C(models.Model):
    a = models.ForeignKey('A')

    def save(self, *args, **kwargs):
        super(C, self).save(*args, **kwargs)
        print 'C.save ', datetime.datetime.now()

    def delete(self, *args, **kwargs):
        super(C, self).delete(*args, **kwargs)
        print 'C.delete ', datetime.datetime.now()




@receiver(models.signals.pre_save)
def my_pre_save(sender, instance, using, **kwargs):
    print type(sender), sender.__name__
    print type(instance), instance
    print using
    print kwargs
    print 'my_pre_save'


@receiver(models.signals.post_save)
def my_post_save(sender, instance, using, **kwargs):
    print type(sender), sender.__name__
    print type(instance), instance
    print using
    print kwargs
    print 'my_post_save'





@receiver(models.signals.pre_delete)
def my_pre_delete(sender, instance, using, **kwargs):
    print sender, type(sender)
    print instance, type(instance)
    print using, type(using)
    if sender.__name__ == 'B':
        print 'pre_delete B'
        o = A.objects.get(pk=1)
        o.count -= 1
        o.save()

    if sender.__name__ == 'C':
        print 'pre_delete C'
        o = A.objects.get(pk=1)
        o.count -= 1
        o.save()


@receiver(models.signals.post_delete)
def my_post_delete(sender, instance, using, **kwargs):
    modelName = sender.__name__
    print sender, type(sender)
    print instance, type(instance)
    print using, type(using)
    if modelName == 'A':
        print 'post_delete A'
        import time
        time.sleep(10)
        b = B.objects.all()[0]
        b.number = 999
        b.save()

    if modelName == 'B':
        print 'post_delete B'
        o = A.objects.get(pk=1)
        o.count += 1
        o.save()

    if modelName == 'C':
        print 'post_delete C'
        o = A.objects.get(pk=1)
        o.count += 1
        o.save()
